#!/usr/bin/env bash

prep() {
    %autosetup -n %{name} -p1
}

build() {
    cmake
    
    %make_build
    
}

cmake() {
    %cmake . %{?build_cmake_flags} \
            -DCMAKE_BUILD_TYPE=RelWithDebInfo \
            -DREVISION_LAST=%{version} -DREVISION=%{version} -DPYTHON_CMD=python3 \
            -DCMAKE_USE_LIBBPF_PACKAGE:BOOL=FALSE \
            %{?with_llvm_shared:-DENABLE_LLVM_SHARED=1}
    
}

install() {
    %make_install
    
    # Fix python shebangs
    find %{buildroot}%{_datadir}/%{name}/{tools,examples} -type f -exec \
      sed -i -e '1s=^#!/usr/bin/python\([0-9.]\+\)\?$=#!%{__python3}=' \
             -e '1s=^#!/usr/bin/env python\([0-9.]\+\)\?$=#!%{__python3}=' \
             -e 's/from bcc/from bpfcc/g' \
             -e 's/import bcc/import bpfcc/g' \
             -e 's/bcc\./bpfcc\./g' \
             -e '1s=^#!/usr/bin/env bcc-lua$=#!/usr/bin/bcc-lua=' {} \;
    
    # Move man pages to the right location
    mkdir -p %{buildroot}%{_mandir}
    mv %{buildroot}%{_datadir}/%{name}/man/* %{buildroot}%{_mandir}/
    
    mv %{buildroot}%{python3_sitelib}/%{name} %{buildroot}%{python3_sitelib}/bpfcc
    rename %{name} bpfcc %{buildroot}%{python3_sitelib}/%{name}-*egg-info
    
    # Avoid conflict with other manpages
    # https://bugzilla.redhat.com/show_bug.cgi?id=1517408
    for i in `find %{buildroot}%{_mandir} -name "*.gz"`; do
    tname=$(basename $i)
    rename $tname %{name}-$tname $i
    done
    mkdir -p %{buildroot}%{_docdir}/%{name}
    mv %{buildroot}%{_datadir}/%{name}/examples %{buildroot}%{_docdir}/%{name}/
    
    # Delete old tools we don't want to ship
    rm -rf %{buildroot}%{_datadir}/%{name}/tools/old/
    
    # We cannot run the test suit since it requires root and it makes changes to
    # the machine (e.g, IP address)
    #%check
    
    %ldconfig_scriptlets
}

